package cn.com.dcsgo.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 持久层配置
 *
 * @author Dcsgo
 * @since 2025/3/8 16:09
 */
@Configuration
public class MyBatisConfig {
    /**
     * mybatis-spring提供了一个FactoryBean我们将其装配到
     * IoC容器后便可以获取到sqlSessionFactory
     * 配置文件中的所有配置都可以通过SqlSessionFactoryBean完成
     *
     * @param dataSource dataSource
     * @return SqlSessionFactoryBean
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        //settings 配置
        org.apache.ibatis.session.Configuration configuration =
                new org.apache.ibatis.session.Configuration();
        //开启表字段->下划线与类属性->驼峰映射
        configuration.setMapUnderscoreToCamelCase(true);
        //结果集映射 自动映射复杂结构集
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        //日志输出
        configuration.setLogImpl(Slf4jImpl.class);
        sqlSessionFactoryBean.setConfiguration(configuration);

        //类型别名配置
        sqlSessionFactoryBean.setTypeAliasesPackage("cn.com.dcsgo.pojo");

        //插件配置 分页插件配置
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.setProperties(properties);
        sqlSessionFactoryBean.setPlugins(pageInterceptor);

        return sqlSessionFactoryBean;
    }

    /**
     * 1.要扫描的Mapper接口
     * 2.自动注册 MapperFactoryBean
     * 3.支持注解和过滤器，如 @Mapper 来筛选需要扫描的接口
     * 4.自动加载与 Mapper 接口位于同一包内的映射文件
     *
     * @return MapperScannerConfigurer
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("cn.com.dcsgo.mapper");
        return mapperScannerConfigurer;
    }
}
